package org.apache.dubbo.remoting.exchange.support;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public final class MultiMessage<T> implements Iterable<T> {

    private final List<T> messages = new ArrayList<>();

    private MultiMessage() {

    }

    public static <T> MultiMessage<T> createFromCollection(Collection<T> collection) {
        MultiMessage<T> multiMessage = new MultiMessage<>();
        multiMessage.addMessages(collection);
        return multiMessage;
    }

    public static <T> MultiMessage<T> createFromArray(T... args) {
        return createFromCollection(Arrays.asList(args));
    }

    public static <T> MultiMessage<T> create() {
        return new MultiMessage<>();
    }

    public void addMessage(T msg) {
        messages.add(msg);
    }

    public void addMessages(Collection<T> collection) {
        messages.addAll(collection);
    }

    public int size() {
        return messages.size();
    }

    public T get(int index) {
        return messages.get(index);
    }

    public boolean isEmpty() {
        return messages.isEmpty();
    }

    public Collection<T> removeMessages() {
        Collection<T> results = Collections.unmodifiableCollection(messages);
        messages.clear();
        return results;
    }

    @Override
    public Iterator<T> iterator() {
        return messages.iterator();
    }
}
